<template>
  <view class="message-item" @click="handleItemClick">
    <image class="avatar" :src="avatarUrl" mode="aspectFill"></image>
    <view class="message-content">
      <view class="username">{{ username }}</view>
      <view class="last-message">{{ lastMessage }}</view>
    </view>
    <view class="unread-count" v-if="unreadCount > 0">{{ unreadCount }}</view>
  </view>
</template>

<script setup>
import { ref,computed } from 'vue';

// 接收外部传入的头像地址、用户名、最后一条消息和未读消息条数
const props = defineProps({
  avatar: {
    type: String,
    default: '/static/picture/defaulAvatar.png',
  },
  username: {
    type: String,
    required: true
  },
  lastMessage: {
    type: String,
    default: '',
  },
  unreadCount: {
    type: Number,
    default: 0
  },
  userId: {
    type: [String, Number],
    default: ''
  },

});
// 计算最终使用的头像地址：如果传入的 avatar 是 null，则用默认值
const avatarUrl = computed(() => {
  // 若 props.avatar 为 null 或 undefined，返回默认头像；否则返回传入的头像
  return props.avatar || '/static/picture/defaulAvatar.png';
});
// 定义事件发射器，用于向父组件传递事件
const emit = defineEmits(['close-socket']);

// 点击事件处理函数：跳转到聊天页面
const handleItemClick = () => {
  // 1. 触发自定义事件，通知父组件关闭WebSocket连接
  emit('close-socket');
  // 使用 uni-app 原生路由跳转（支持多端）
  uni.navigateTo({
    // 拼接跳转地址，参数为当前用户的信息
    url: `/pages/message/chat?userId=${props.userId}&name=${props.username}&avatar=${props.avatar}`
  });
};
</script>

<style scoped>
.message-item {
  display: flex;
  align-items: center;
  padding: 10px;
  position: relative;
}
.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin-right: 10px;
}
.message-content {
  flex: 1;
  overflow: hidden;
}
.username {
  font-size: 15px;
}
.last-message {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.unread-count {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ff4500;
  color: white;
  font-size: 12px;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
